package cn.edu.ncut.cs.springboot.petmanagementsystem.controller;

import cn.edu.ncut.cs.springboot.petmanagementsystem.common.Result;
import cn.edu.ncut.cs.springboot.petmanagementsystem.dto.AddressRequest;
import cn.edu.ncut.cs.springboot.petmanagementsystem.pojo.Address;
import cn.edu.ncut.cs.springboot.petmanagementsystem.service.AddressService;
import cn.edu.ncut.cs.springboot.petmanagementsystem.service.UserService;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 * 收货地址控制器
 */
@Slf4j
@RestController
@RequestMapping("/address")
@Tag(name = "收货地址模块")
public class AddressController {

    @Autowired
    private AddressService addressService;

    @Autowired
    private UserService userService;

    @Operation(summary = "获取收货地址列表")
    @GetMapping("/list")
    public Result<List<Address>> getAddressList() {
        try {
            Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
            String username = authentication.getName();
            var user = userService.getUserByUsername(username);
            if (user == null) {
                return Result.error("用户不存在");
            }

            List<Address> addressList = addressService.getAddressList(user.getId());
            return Result.success("查询成功", addressList);
        } catch (Exception e) {
            log.error("获取收货地址列表失败", e);
            return Result.error("查询失败: " + e.getMessage());
        }
    }

    @Operation(summary = "添加收货地址")
    @PostMapping("/add")
    public Result<Address> addAddress(@RequestBody AddressRequest request) {
        try {
            Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
            String username = authentication.getName();
            var user = userService.getUserByUsername(username);
            if (user == null) {
                return Result.error("用户不存在");
            }

            // 构建Address对象
            Address address = new Address();
            address.setReceiverName(request.getReceiverName());
            address.setReceiverPhone(request.getReceiverPhone());
            address.setProvince(request.getProvince());
            address.setCity(request.getCity());
            address.setDistrict(request.getDistrict());
            address.setDetailAddress(request.getDetailAddress());

            Address savedAddress = addressService.addAddress(user.getId(), address);
            return Result.success("添加成功", savedAddress);
        } catch (IllegalArgumentException e) {
            return Result.error(e.getMessage());
        } catch (Exception e) {
            log.error("添加收货地址失败", e);
            return Result.error("添加失败: " + e.getMessage());
        }
    }

    @Operation(summary = "更新收货地址")
    @PutMapping("/update/{id}")
    public Result<?> updateAddress(
            @Parameter(description = "地址ID") @PathVariable Long id,
            @RequestBody AddressRequest request) {
        try {
            Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
            String username = authentication.getName();
            var user = userService.getUserByUsername(username);
            if (user == null) {
                return Result.error("用户不存在");
            }

            // 构建Address对象
            Address address = new Address();
            address.setReceiverName(request.getReceiverName());
            address.setReceiverPhone(request.getReceiverPhone());
            address.setProvince(request.getProvince());
            address.setCity(request.getCity());
            address.setDistrict(request.getDistrict());
            address.setDetailAddress(request.getDetailAddress());

            boolean success = addressService.updateAddress(id, user.getId(), address);
            return success ? Result.success("更新成功") : Result.error("更新失败");
        } catch (IllegalArgumentException e) {
            return Result.error(e.getMessage());
        } catch (Exception e) {
            log.error("更新收货地址失败", e);
            return Result.error("更新失败: " + e.getMessage());
        }
    }

    @Operation(summary = "删除收货地址")
    @DeleteMapping("/{id}")
    public Result<?> deleteAddress(@Parameter(description = "地址ID") @PathVariable Long id) {
        try {
            Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
            String username = authentication.getName();
            var user = userService.getUserByUsername(username);
            if (user == null) {
                return Result.error("用户不存在");
            }

            boolean success = addressService.deleteAddress(id, user.getId());
            return success ? Result.success("删除成功") : Result.error("删除失败");
        } catch (IllegalArgumentException e) {
            return Result.error(e.getMessage());
        } catch (Exception e) {
            log.error("删除收货地址失败", e);
            return Result.error("删除失败: " + e.getMessage());
        }
    }

    @Operation(summary = "设置默认地址")
    @PutMapping("/set-default/{id}")
    public Result<?> setDefaultAddress(@Parameter(description = "地址ID") @PathVariable Long id) {
        try {
            Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
            String username = authentication.getName();
            var user = userService.getUserByUsername(username);
            if (user == null) {
                return Result.error("用户不存在");
            }

            boolean success = addressService.setDefaultAddress(id, user.getId());
            return success ? Result.success("设置成功") : Result.error("设置失败");
        } catch (IllegalArgumentException e) {
            return Result.error(e.getMessage());
        } catch (Exception e) {
            log.error("设置默认地址失败", e);
            return Result.error("设置失败: " + e.getMessage());
        }
    }

    @Operation(summary = "获取默认地址")
    @GetMapping("/default")
    public Result<Address> getDefaultAddress() {
        try {
            Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
            String username = authentication.getName();
            var user = userService.getUserByUsername(username);
            if (user == null) {
                return Result.error("用户不存在");
            }

            Address address = addressService.getDefaultAddress(user.getId());
            if (address != null) {
                return Result.success("查询成功", address);
            }
            return Result.error("暂无默认地址");
        } catch (Exception e) {
            log.error("获取默认地址失败", e);
            return Result.error("查询失败: " + e.getMessage());
        }
    }
}
